import React from 'react';
import {
    Table,
} from 'antd';

function getType(o) {
    return Object.prototype.toString.call(o).slice(8, -1);
}

function getDateString(d) {
    const pad = (i) => i.toString().padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

export function formatTime(a) {
    if (a) {
        if (a.format) {
            return a.format('YYYY-MM-DD HH:mm:ss');
        } else {
            const d = new Date(a);
            return getDateString(d);
        }
    }
    return a;
}

export function convertRes2Blob(response, filename = 'untitled') {
    const blob = new Blob([response], {
        type: 'application/vnd.ms-excel', // Office 2003 format
        // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // Office 2007 format
    });
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename);
    } else {
        const blobURL = window.URL.createObjectURL(blob);
        const tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', filename);
        if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank');
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
    }
}

export const BasicTable = React.memo(function BasicTable({ rowKey, pagination, ...props }) {
    const rowKeyProp = rowKey ? rowKey : (row, index) => index;
    const paginationOption = getType(pagination) === 'Object' ? {
        // showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条数据`,
        ...pagination,
    } : false;

    return (
        <Table
            className="x-basictable"
            size="small"
            rowKey={rowKeyProp}
            pagination={paginationOption}
            {...props} />
    );
});
